package control;

import java.awt.Desktop;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import model.FileVO;
import model.GenericTreeNode;

public class FileManager {
	
	ArrayList<GenericTreeNode<FileVO>> cachedFiles = new ArrayList<GenericTreeNode<FileVO>>();
	
	public void openFile(File file) throws IOException {
		if(file.exists()) {
			Desktop.getDesktop().open(new File(file.getAbsolutePath()));
		}
	}
	
	public void copyFiles(List<GenericTreeNode<FileVO>> filesToCopy, GenericTreeNode<FileVO> target) throws IOException {
		for (GenericTreeNode<FileVO> file : filesToCopy) {
			copyFile(file, target);
		}
	}
	
	public void cutFiles(List<GenericTreeNode<FileVO>> files, GenericTreeNode<FileVO> target) throws IOException {
		copyFiles(files, target);
		removeFiles(files);		
	}
	
	public void removeFiles(List<GenericTreeNode<FileVO>> filesToRemove) {
		for (GenericTreeNode<FileVO> file : filesToRemove) {
			if (file.getData().list() != null && file.getData().list().length > 0) {
				removeFile(file.getData().getAbsoluteFile());
			}
			file.getData().delete();
		}
	}
	
	private void removeFile(File file) {
		for (File f : file.listFiles()) {
			removeFile(f);
			f.delete();
		}		
	}
	
	private void copyFile(GenericTreeNode<FileVO> fileToCopy, GenericTreeNode<FileVO> target) throws IOException {
		
		File inputFile = fileToCopy.getData().getAbsoluteFile();
		File outputFile = new File(target.getData().getAbsoluteFile() + "\\" + inputFile.getName());

		FileReader in = new FileReader(inputFile);
		FileWriter out = new FileWriter(outputFile);
		int c;

		while ((c = in.read()) != -1)
			out.write(c);

		in.close();
		out.close();	
	}

	public void createFolder(GenericTreeNode<FileVO> dir) {
		dir.getData().mkdir();
	}
}
